package com.cdm.qf.autoconfig;

import com.alibaba.druid.pool.DruidDataSource;
import com.cdm.qf.pojo.DsProperties;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(DsProperties.class)
public class CdmMybatisAutoConfiguration {

    @Autowired
    private DsProperties dsProperties;


    @Bean
    public DataSource ds(){
        DruidDataSource dataSource = new DruidDataSource();
        //设置数据库的4个信息
        dataSource.setDriverClassName(dsProperties.getDriver());
        dataSource.setUrl(dsProperties.getUrl());
        dataSource.setUsername(dsProperties.getUsername());
        dataSource.setPassword(dsProperties.getPassword());

        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean ssfb(DataSource ds){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(ds);
        return ssfb;
    }

    /**
     * MapperScannerConfigurer对象本质是一个BeanFactoryPostProcessor（bean工厂的后置处理器）
     * 这种类型的对象是在所有其他普通类型对象之前创建，之前执行
     * 在创建这个MapperScannerConfigurer之前，dsProperties还没有被创建，所以这个地方拿不到dsProperties属性值
     * 这种方式就不可用了
     * @return
     */
   /* @Bean
    public static MapperScannerConfigurer msc(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();

        msc.setBasePackage(dsProperties.getBasePackage());

        return msc;
    }*/
}
